﻿using System;

using zijian666.Converts.Abstractions;
using zijian666.Converts.Core;
using zijian666.Converts.Extensions;

namespace zijian666.Converts.Convertor.Base;

/// <summary>
/// 表示一个异常的转换器
/// </summary>
/// <typeparam name="T"></typeparam>
public class ErrorConvertor<T> : IConvertor<T>
{
    /// <summary>
    /// 表示一个异常的转换器
    /// </summary>
    /// <param name="typeFriendlyName">类型名称</param>
    /// <param name="reason">异常原因</param>
    public ErrorConvertor(string typeFriendlyName, string reason)
    {
        if (string.IsNullOrWhiteSpace(typeFriendlyName))
        {
            throw new ArgumentException($"“{nameof(typeFriendlyName)}”不能为 null 或空白。", nameof(typeFriendlyName));
        }

        if (string.IsNullOrWhiteSpace(reason))
        {
            throw new ArgumentException($"“{nameof(reason)}”不能为 null 或空白。", nameof(reason));
        }

        TypeFriendlyName = typeFriendlyName;
        Reason = reason;
    }

    /// <summary>
    /// 创建一个异常的转换器
    /// </summary>
    /// <param name="reason">异常原因</param>
    public ErrorConvertor(string reason)
    {
        if (string.IsNullOrWhiteSpace(reason))
        {
            throw new ArgumentException($"“{nameof(reason)}”不能为 null 或空白。", nameof(reason));
        }

        TypeFriendlyName = typeof(T).GetFriendlyName();
        Reason = reason;
    }

    /// <inheritdoc />
    public ConvertResult<T> Convert(IConvertContext context, object? input)
    {
        if (context is null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        return ExceptionHelper.CantBuildConvertor(TypeFriendlyName, Reason, context.Settings.CultureInfo);
    }

    /// <inheritdoc />
    public uint Priority { get; } = 0;

    /// <summary>
    /// 类型名称
    /// </summary>
    public string TypeFriendlyName { get; }

    /// <summary>
    /// 异常原因
    /// </summary>
    public string Reason { get; }
}
